﻿
using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using S7.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    public class InitPlcHosetService : BackgroundService
    {
        private readonly Plc plc;
        private readonly PlcHeartbeatTool plcHeartbeatTool;
        private readonly ILogger<InitPlcHosetService> logger;

        public InitPlcHosetService(Plc plc,PlcHeartbeatTool plcHeartbeatTool,ILogger<InitPlcHosetService> logger)
        {
            this.plc = plc;
            this.plcHeartbeatTool = plcHeartbeatTool;
            this.logger = logger;
        }

        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {

            try
            {
                while (true)
                {
                    try
                    {
                        if (plc.IsConnected == false)
                        {
                            plc.Open();
                            plcHeartbeatTool.StartHeartbeat();
                            logger.LogInformation("WCS启动成功");
                        }
                        await Task.Delay(5000);
                    }
                    catch (PlcException ex)
                    {
                        logger.LogError("WCS程序失败:" + ex.Message, ex);
                        await Task.Delay(5000);
                        continue; 
                    }
                }

                
            }
            catch (Exception ex)
            {
                logger.LogError("WCS程序失败:"+ex.Message, ex);
            }
            StopAsync(stoppingToken);


        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Dispose();
            logger.LogInformation("程序启动成功,已正常释放任务");
            return base.StopAsync(cancellationToken);
        }
    }
}
